package jp.sinmetal.trainer.service;

import java.util.Date;
import java.util.List;

import jp.sinmetal.trainer.entity.Convention;
import jp.sinmetal.trainer.util.DateUtil;

import static org.seasar.extension.jdbc.operation.Operations.asc;
import static org.seasar.extension.jdbc.operation.Operations.desc;

/**
 * 大会サービス
 * @author sin
 *
 */
public class ConventionService extends AbstractService<Convention> {

    /**
     * 大会IDを基にエンティティを返す
     * @author sin
     *
     * @param conventionId
     * @return
     */
    public Convention findById(Integer conventionId) {
        return select()
        	.innerJoin("member")
        	.leftOuterJoin("conventionMembers").leftOuterJoin("conventionMembers.member")
        	.id(conventionId)
        	.orderBy(desc("conventionMembers.winCount"), asc("conventionMembers.winDate"))
        	.getSingleResult();
    }

    /**
     * 大会一覧を返す
     * @author sin
     *
     * @return
     */
    public List<Convention> findAllConvention() {
    	return select().innerJoin("member").orderBy(desc("entryDate")).getResultList();
    }

    /**
     * 大会作成
     * @author sin
     *
     * @param entity
     * @return
     */
    public int insertConvention(Convention entity) {
    	Date today = DateUtil.getNow();
    	entity.entryDate = today;
    	entity.updateDate = today;

    	return jdbcManager.insert(entity).execute();
    }

    /**
     * 大会更新
     * @author sin
     *
     * @param entity
     * @return
     */
    public int updateConvention(Convention entity) {
    	if (!isOwner(entity)) {
    		return 0;
    	}

    	Date today = DateUtil.getNow();
    	entity.updateDate = today;

    	return jdbcManager.update(entity).excludes("entryDate").execute();
    }

    /**
     * Entityのオーナーが自分かを返す
     * @author sin
     *
     * @param entity
     * @return
     */
    protected boolean isOwner(Convention entity) {
    	Convention convention = findById(entity.conventionId);
    	if (convention == null) {
    		return false;
    	}
    	return (convention.memberId.equals(entity.memberId));
    }
}